package com.xx.happychatboot.serve.room.service.impl;

import com.xx.happychatboot.base.utils.GenerateKeyUtils;
import com.xx.happychatboot.middleware.rocketmq.utils.RocketMqProducer;
import com.xx.happychatboot.serve.room.domain.entity.GroupMember;
import com.xx.happychatboot.serve.room.domain.entity.Room;
import com.xx.happychatboot.serve.room.domain.entity.RoomFriend;
import com.xx.happychatboot.serve.room.domain.enums.RoomTypeEnum;
import com.xx.happychatboot.serve.room.mapper.GroupMemberMapper;
import com.xx.happychatboot.serve.room.mapper.RoomMapper;
import com.xx.happychatboot.serve.room.service.IGroupMemberService;
import com.xx.happychatboot.serve.room.service.IRoomFriendService;
import com.xx.happychatboot.serve.room.service.IRoomService;
import io.mybatis.service.AbstractService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Objects;

@Service
public class RoomServiceImpl extends AbstractService<Room, Long, RoomMapper> implements IRoomService {
    @Autowired
    private RoomMapper roomMapper;

    @Autowired
    private IRoomFriendService roomFriendService;

    @Autowired
    private ApplicationContext applicationContext;

    /**
     * 创建房间
     *
     * @param uid      用户id
     * @param targetId 目标用户id
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void creatRoom(Long uid, Long targetId) {
        if (Objects.isNull(uid) || Objects.isNull(targetId)) {
            throw new RuntimeException("创建房间出现异常，请联系管理员");
        }

        // 判断房间是否存在 ( 两个用户之间只能有一个房间 )
        String key = GenerateKeyUtils.generateRoomKey(uid, targetId);
        RoomFriend roomFriend = roomFriendService.getRoomByRoomKey(key);

        if (Objects.nonNull(roomFriend)) {
            // 如果存在房间就恢复，适用于恢复好友场景
            roomFriendService.restoreRoomIfNeed(roomFriend);

        } else {
            // 新建房间
            // 获取当前代理对象并调用 createRoom 方法 --- 避免事务失效
            RoomServiceImpl proxy = applicationContext.getBean(RoomServiceImpl.class);
            Room room = proxy.createRoom(RoomTypeEnum.FRIEND);

            // 创建好友房间
            roomFriend = roomFriendService.createFriendRoom(room.getId(), uid, targetId);
        }

        //todo 发送一条同意消息。。我们已经是好友了，开始聊天吧

    }

    /**
     * 创建房间
     *
     * @param typeEnum
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public Room createRoom(RoomTypeEnum typeEnum) {
        Room insert = Room.buildRoom(typeEnum);
        roomMapper.insert(insert);
        return insert;
    }
}
